package com.fish.manni;

import javax.imageio.ImageIO;
import javax.swing.*;

import org.apache.commons.io.FileUtils;

import javafx.event.ActionEvent;
import javafx.scene.input.KeyEvent;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * JPanel 是一种中间层容器，它能容纳组件并将组件组合在一起，但它本身必须添加到其他容器中使用。JPanel 类的构造方法如下。
 * 上述contentPane实际上就是一个JPanel。Jframe中会默认new一个JPanel，塞入JFrame中。有一个很形象的比喻，JFrame是一个
 * 桌子，各个组件是一盘盘菜，而JPanel就是一个菜盘，装了各个组件以后放到桌上。一个JFrame界面上可以有多个JPanel用来划分
 * 不同的区域。
 */
public class FrameTest {
    static int xx;
    static int yy;
    static String qqnicheng = "";
    static String groupName = "";
    static int renshu = 300;
    public static void main(String[] args) {
        EndListener endListener = new EndListener();
        // 创建窗口
        JFrame window1 = new JFrame("qq脚本");
        JPanel jPanel = new JPanel(); // 创建面板

        TextField jtf_nicheng = new TextField(); // 文本框
        // jtf.setBounds(10, 10, 150, 30);
        // jtf_nicheng.setSize(500, 150);
        jtf_nicheng.setColumns(8);
        TextField jtf_groupname = new TextField(); // 文本框
        jtf_groupname.setColumns(8);
        TextField jtf__renshu = new TextField(); // 文本框
        jtf__renshu.setColumns(8);
        // jtf.setBounds(10, 10, 150, 30);
        // Container con = window1.getContentPane(); //用getContentPane()方法获得JFrame的内容面板
        // con.setBackground(Color.blue); //设置背景颜色为蓝色

        // 距离屏幕左边100个像素，上边100个像素，窗口的宽是300，高是300
        window1.setBounds(550, 350, 450, 360); // 设置窗口1在屏幕上的位置及大小

        // 设置文字
        // JLabel jLabel = new JLabel("阿涛来了");
        // window1.add(jLabel);
        // 让文本标签水平居中
        // jLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 边框布局
        // jPanel.setLayout(new BorderLayout());//设置边框布局

        // 流式布局
        // 向JPanel添加FlowLayout布局管理器，将组件间的横向和纵向间隙都设置为20像素
        // FlowLayout(int align, int hgap,int vgap)组件对齐方式以及横纵隔距离
        jPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 20, 20));
        // 如果想设置横纵向间隔使用方法BorderLayout(int hgap,int vgap)

        JLabel jLabel = new JLabel("异常情况按 'Esc' 结束程序");
        JLabel jLabel_nicheng = new JLabel("qq昵称");
        JLabel jLabel_groupname = new JLabel("qq群名");
        JLabel jLabel__renshu = new JLabel("群人数");

        JLabel jLabe2 = new JLabel("使用方法: 输入qq群成员数量,默认300");
        JLabel jLabe3 = new JLabel("点击 '开始定位' 按钮,将鼠标移动至qq群成员");
        JLabel jLabe4 = new JLabel("列表第一位用户,期间只移动鼠标,不要进行");
        JLabel jLabe5 = new JLabel("任何按键操作,按下  'A'  结束定位");

        JLabel jLabe6 = new JLabel("点击 '运行脚本' 按钮开始运行");

        jPanel.add(jLabel_nicheng);
        jPanel.add(jtf_nicheng);
        jPanel.add(jLabel_groupname);
        jPanel.add(jtf_groupname);
        jPanel.add(jLabel__renshu);
        jPanel.add(jtf__renshu);
        jPanel.add(jLabel);
        jPanel.add(jLabe2);
        jPanel.add(jLabe3);
        jPanel.add(jLabe4);
        jPanel.add(jLabe5);
        jPanel.add(jLabe6);

        File qqtext = new File("D://qq.txt");
        File qqname = new File("D://qq昵称.txt");
        File log = new File("D://qq_script_log.txt");
        JButton button1 = new JButton("开始定位");
        button1.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(java.awt.event.KeyEvent e) {
            }

            @Override
            public void keyPressed(java.awt.event.KeyEvent e) {
                String a = java.awt.event.KeyEvent.getKeyText(e.getKeyCode());
                if ("向上箭头".equals(a)) {
                    System.exit(0);
                }
                // 获取鼠标指针的信息
                PointerInfo pointerInfo = MouseInfo.getPointerInfo();
                // 获取鼠标的当前位置
                java.awt.Point point = pointerInfo.getLocation();
                // 获取X轴和Y轴的位置

                if ("A".equalsIgnoreCase(a)) {
                    xx = (int) point.getX();
                    yy = (int) point.getY();
                    System.out.println("A定位结束  " + xx + "   " + yy);
                    qqnicheng = jtf_nicheng.getText();
                    groupName = jtf_groupname.getText();
                    try{
                        renshu = Integer.parseInt(jtf__renshu.getText());
                    }catch(Exception ee){
                        log(log, "人数输入结果解析错误");
                        ee.printStackTrace();
                    }
                    
                }
            }

            @Override
            public void keyReleased(java.awt.event.KeyEvent e) {
            }

        });
        JButton button2 = new JButton("运行脚本");
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try {
                    Robot myRobot = new Robot();
                    myRobot.setAutoDelay(200);
                    // myRobot.setAutoWaitForIdle(true);
                    myRobot.mouseMove(xx, yy);
                    int isqqnicheng = 0;
                    boolean flag = false;
                    for (int i = 0; i < renshu; i++) {
                        Thread.sleep(400);
                        myRobot.mousePress(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                        myRobot.mouseRelease(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                        myRobot.mousePress(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                        myRobot.mouseRelease(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                        // 定义要截取的区域
                        // 创建一个Toolkit对象
                        Toolkit toolkit = Toolkit.getDefaultToolkit();
                        // 获取屏幕尺寸
                        Dimension screenSize = toolkit.getScreenSize();
                        int screenWidth = screenSize.width;
                        int screenHeight = screenSize.height;
                        // 获取屏幕分辨率
                        int screenResolution = toolkit.getScreenResolution();

                        Rectangle rect = new Rectangle((screenWidth-430)/2, 0, 430, 38);
                        // 截取屏幕
                        BufferedImage image = myRobot.createScreenCapture(rect);
                        String img64 = ImageUtil.convertImageToBase64Str(image);
                        String res = ImageUtil.shibieshuzi(img64);
                        String nums = ImageUtil.extractNumbers(res);
                        // 保存截图

                        // String currentDirectory = System.getProperty("user.dir");
                        // System.out.println("当前程序所在路径：" + currentDirectory);
                        // String dizhiPath = currentDirectory+File.separator;

                        File f = new File("D://" + UUID.randomUUID() + ".png");
                        ImageIO.write(image, "png", f);
                        log(log, res);
                        if (qqnicheng.length() > 10) {
                            qqnicheng = qqnicheng.substring(1, 10);
                        }
                        if (groupName.length() > 10) {
                            groupName = groupName.substring(1, 10);
                        }
                        FileUtils.writeStringToFile(qqtext, nums + "\r\n", "utf-8", true);
                        FileUtils.writeStringToFile(qqname, res + "\r\n", "utf-8", true);
                        if (res.contains(qqnicheng)) {
                            log(log, "包含群名");
                            isqqnicheng++;
                            if (isqqnicheng == 1) {
                                myRobot.keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.mouseMove(xx, yy + 7);
                                yy += 7;

                            }
                            if (isqqnicheng == 2) {
                                myRobot.keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.mouseMove(xx, yy + 7);
                                yy += 7;

                            }

                            if (isqqnicheng == 3) {
                                myRobot.keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
                                myRobot.mouseMove(xx, yy + 7);
                                yy += 7;
                            }
                            if(isqqnicheng == 4){
                                log(log,"解析结果一直是 昵称 isqqnicheng == 4");
                                System.exit(0);
                            }
                        } else if (res.contains(groupName)) {
                            log(log, "包含群名");
                            flag = true;
                            myRobot.mouseMove(xx, yy + 7);
                            yy += 7;
                            myRobot.mousePress(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                            myRobot.mouseRelease(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                            myRobot.mousePress(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                            myRobot.mouseRelease(java.awt.event.KeyEvent.BUTTON1_DOWN_MASK);
                        } else if (flag) {
                            log(log, "flag true");
                            myRobot.keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                            myRobot.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
                            myRobot.mouseMove(xx, yy + 12);
                            yy += 12;
                        } else if (null != nums && nums.length() > 1) {
                            log(log, "有数字");
                            myRobot.keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                            myRobot.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);
                            myRobot.mouseWheel(1); // 向下滚动1个单位
                        } else {
                            log(log,"解析结果不包含昵称或群名,也不是成员qq号");
                            System.exit(0);
                        }

                        flag = false;
                    }
                } catch (InterruptedException e1) {
                    log(log, e1);
                    e1.printStackTrace();
                } catch (IOException e1) {
                    log(log, e1);
                    e1.printStackTrace();
                } catch (AWTException e1) {
                    log(log, e1);
                    e1.printStackTrace();
                }
            }
        });
        // JButton button3=new JButton("中");
        // JButton button4=new JButton("右");
        // JButton button5=new JButton("下");
        jPanel.add(button1);
        jPanel.add(button2);
        // jPanel.add(button3,BorderLayout.CENTER);
        // jPanel.add(button4,BorderLayout.EAST);
        // jPanel.add(button5,BorderLayout.SOUTH);
        window1.add(jPanel);
        window1.addKeyListener(endListener);

        window1.setVisible(true); // 设置窗口可见
        window1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 释放当前窗口

    }
    static void log(File log, Exception e){
        try {
            FileUtils.writeStringToFile(log, e.getLocalizedMessage()+"\r\n", "utf-8", true);
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
    static void log(File log, String s){
        try {
            FileUtils.writeStringToFile(log, s+"\r\n", "utf-8", true);
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
}

// 弹窗的窗口
class MyDialog extends JDialog {

    public MyDialog() throws InterruptedException {

        this.setVisible(true);
        this.setBounds(100, 100, 500, 500);
        // this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(null);
        container.add(new Label("请输入数字!"));
        Thread.sleep(1000 * 5);
        System.exit(0);
    }
}
